package com.parktech.sun.domain.service.impl;

import com.parktech.sun.domain.model.ContentEntity;
import com.parktech.sun.domain.repository.BaseRepository;
import com.parktech.sun.domain.repository.IndexRepository;
import com.parktech.sun.domain.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 11-1-8
 * Time: 下午9:37
 * To change this template use File | Settings | File Templates.
 */
public class BaseServiceImpl<T> implements BaseService<T> {

    private BaseRepository<T> baseRepository;

    private IndexRepository indexRepository;

    private boolean isContentEntityGeneric;

    @SuppressWarnings("unchecked")
    public BaseServiceImpl() {
        Class clazz = (Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
        isContentEntityGeneric = ContentEntity.class.isAssignableFrom(clazz);
    }

    @Autowired
    public void setIndexRepository(IndexRepository indexRepository) {
        this.indexRepository = indexRepository;
    }

    @SuppressWarnings("unchecked")
    public BaseServiceImpl(BaseRepository<T> baseRepository) {
        this.baseRepository = baseRepository;
        Class clazz = (Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
        isContentEntityGeneric = ContentEntity.class.isAssignableFrom(clazz);
    }

    public BaseRepository<T> getBaseRepository() {
        return baseRepository;
    }

/*    public void setBaseRepository(BaseRepository<T> baseRepository) {
        this.baseRepository = baseRepository;
    }*/

    public T getById(Long id) {
        return baseRepository.getBeanById(id);
    }

    /**
     * 所有模块都可调用的公共分页显示方法，获取满足模糊条件的对象的总数目
     *
     * @param clz
     * @param fieldColumns
     * @param searchValues
     * @return
     */
    public Integer getTotalSizeWithSimilarCondition(Class clz, List fieldColumns, List searchValues) {
        return baseRepository.getTotalSizeWithSimilarCondition(clz, fieldColumns, searchValues);
    }

    /**
     * 所有模块都可调用的公共分页显示方法，获取满足模糊条件的当前分页的对象列表
     * getPaginationObjectsWithSimilarCondition(class,1,20,list['a','b'],lit['avalue','bvlaue'],string["asc","desc"],string[fiede,field])
     *
     * @param clz          对象类
     * @param pageIndex    当前页
     * @param pageSize     每页数目
     * @param fieldColumns 类的属性数组
     * @param searchValues 类的属性数组对应的值数组
     * @param sortSchemas  每个排序的健数组对应的升降序规则：即ASC,DESC 数组
     * @param sortKeys     排序的健数组
     * @return
     */
    public List<T> getPaginationObjectsWithSimilarCondition(Class clz, final int pageIndex, final int pageSize, List fieldColumns, List searchValues, String[] sortSchemas, String[] sortKeys) {
        return baseRepository.getPaginationObjectsWithSimilarCondition(clz, pageIndex, pageSize, fieldColumns, searchValues, sortSchemas, sortKeys);
    }

    public List<T> getPaginationObjectsWithSimilarConditionContainCompare(T clz, final int pageIndex, final int pageSize, List fieldColumns, List searchValues, String[] compareColumns, String[] compareDirections, Object[] compareValues, String[] sortSchemas, String[] sortKeys) {
        return baseRepository.getPaginationObjectsWithSimilarConditionContainCompare(clz, pageIndex, pageSize, fieldColumns, searchValues, compareColumns, compareDirections, compareValues, sortSchemas, sortKeys);
    }


    public void saveOrUpdateBean(T bean) {
        if (bean instanceof ContentEntity) {
            ContentEntity contentEntity = (ContentEntity) bean;
            if (contentEntity.getId() == -1L) {
                baseRepository.saveOrUpdateBean(bean);
                indexRepository.createIndex(contentEntity);
            } else {
                baseRepository.saveOrUpdateBean(bean);
                indexRepository.updateIndex(contentEntity);
            }
        } else {
            baseRepository.saveOrUpdateBean(bean);
        }
    }

    public void update(T bean) {
        baseRepository.update(bean);
        if (bean instanceof ContentEntity) {
            indexRepository.updateIndex((ContentEntity) bean);
        }
    }

    public void clearThenSaveOrUpdateBean(T bean) {
        if (bean instanceof ContentEntity) {
            ContentEntity contentEntity = (ContentEntity) bean;
            if (contentEntity.getId() == -1L) {
                baseRepository.clearThenSaveOrUpdateBean(bean);
                indexRepository.createIndex(contentEntity);
            } else {
                baseRepository.clearThenSaveOrUpdateBean(bean);
                indexRepository.updateIndex(contentEntity);
            }
        } else {
            baseRepository.saveOrUpdateBean(bean);
        }
    }

    /**
     * 逻辑删除对象
     *
     * @param id
     */
    public void removeBeanByLogic(Long id) {
        baseRepository.removeBeanByLogic(id);
        if (isContentEntityGeneric) {
            indexRepository.deleteIndexById(id);
        }
    }

    /**
     * 物理删除对象
     *
     * @param id
     */
    public void removeBean(Long id) {
        baseRepository.removeBean(id);
        if (isContentEntityGeneric) {
            indexRepository.deleteIndexById(id);
        }
    }

    public T getBeanByID(Long id) {
        return baseRepository.getBeanById(id);
    }

    public void deleteAll(Long[] ids) {
        baseRepository.deleteAll(ids);
        if (isContentEntityGeneric) {
            for (Long id : ids) {
                indexRepository.deleteIndexById(id);
            }
        }
    }

    public void deleteAll(Class clazz, Long[] ids) {
        baseRepository.deleteAll(clazz, ids);
        if (ContentEntity.class.isAssignableFrom(clazz)) {
            for (Long id : ids) {
                indexRepository.deleteIndexById(id);
            }
        }
    }

    public T merge(T t) {
        return baseRepository.merge(t);
    }
}
